package com.khson.knows.portal.controller;

import com.khson.knows.portal.exception.ServiceException;
import com.khson.knows.portal.service.IUserService;
import com.khson.knows.portal.vo.RegisterVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@Slf4j  //日志记录
public class SystemController {

    @Autowired
    private IUserService iUserService;
    //注册方法,是post请求
    @PostMapping("/register")
    public String registerStudent(
            //@Validated 表示激活后面类型的spring Valiation验证
            //在需要验证的方法参数后添加指定类型(BindingResule)的参数
            //验证结果会自动赋值到这个参数中
            @Validated RegisterVo registerVo, BindingResult result){
        log.debug("收到注册信息:{}",registerVo);
        if(result.hasErrors()){
            //获得错误信息
            String msg = result.getFieldError().getDefaultMessage();
            //当有验证不通过,直接返回错误信息到 axios
            return msg;
        }
        //Ctrl + Alt + T
        try {
            iUserService.registerStudent(registerVo);
            return "ok";
        } catch (ServiceException e){
            e.printStackTrace();
            return e.getMessage();
        }
    }
}
